<?php
/**
 * 计划任务控制器
 *
 * 1.订单自动确认收货 AutoConfirmReceipt()
 * 2.自动下载远程头像 DownLoadAvatar()
 * 3.行为日志转存SQL actionLogRestore()
 * 
 * @version 2015012712
 * @author Max.Yu <max@jipu.com>
 */

namespace Home\Controller;

use Think\Controller;

class CrontabController extends Controller{

  public function __construct(){
    //关闭代码超时
    set_time_limit(3600);
    //读取站点配置
    $config = api('Config/lists');
    C($config);
  }
  
  /**
   * 测试定时任务
   */
  public function test(){
  	set_log('cron','定时任务','cron');
  }

  /**
   * 执行计划任务
   * 每天23点30分，执行一次
   */
  public function init(){
    //订单自动确认收货
    $this->AutoConfirmReceipt();
    //自动下载远程头像
    $this->DownLoadAvatar();
    //行为日志转存sql
    $this->actionLogRestore();
    
    // 微信
    $this->weixintask(); 
    // 定时过期团购失败
    $this->joinfail();
    // 代理自动返现
    $this->distributeTast(); 
    //分销自动返现
    $this->SdpRecordTast();
    //购物赠送积分自动写入
    $this->autoScoreTast();
    //记录日志
    
    F('crontab/'.date('Y_m_d_H_i_s'), NOW_TIME);
  }
  /**
   * 微信，每小时执行一次
   */
  public function weixintask(){
    S('accessToken_client' ,null);
  }
  /**
   * 推广自动返现
   * 
   */
  public function distributeTast(){
    $max_day = intval( C('DIS_TIME') );
    empty($max_day) && $max_day =15 ;
    $where = array(
      'f.status'      => 0 ,
      'f.flow'        => 'in',
      'f.type'        => 'union_order',
      'o.o_status'    => '202',
      'o.complete_time' => array(array('gt' ,0) ,array('lt' , (time() - C('DIS_TIME')*3600*24 )) ,'and' ),
    );
    $data = M('Finance')->alias('f')->join('__ORDER__ o on o.id =f.order_id')->where($where)->field('f.id,f.uid,f.amount')->select();
    if($data){

      foreach($data as $k => $v){
        $count[$v['uid']] +=$v['amount'] ;
        $ids[] = $v['id'];
      }
      /*foreach($count as $k => $v){
        M('Member')->where('uid ='.$k)->setInc('finance',$v); 
      }*/
      $map['id'] = array('in', $ids);
      M('Finance')->where($map)->setField('status',1);
    }
  }

  /**
   * 代理自动分销返现
   * @author buddha <[email address]>
   */
  public function SdpRecordTast(){
    $max_day = intval( C('MAX_REFUND_CASH_DAY') );
    empty($max_day) && $max_day =15 ;
    $where = array(
      'f.status'      => 0 ,
      'f.flow'        => 'in',
      'f.type'        => 'sdp_order',
      'o.o_status'    => '202',
      'o.complete_time' => array(array('gt' ,0) ,array('lt' , (time() - C('MAX_REFUND_CASH_DAY')*3600*24 )) ,'and' ),
    );

    $data = M('Finance')->alias('f')->join('__ORDER__ o on o.id =f.order_id')->where($where)->field('f.id,f.uid,f.amount')->select();
    if($data){
      foreach($data as $k => $v){
        $count[$v['uid']] +=$v['amount'] ;
        $ids[] = $v['id'];
      }
      $map['id'] = array('in', $ids);
      M('Finance')->where($map)->setField('status',1);
    }
  }

  /**
   * 购物赠送积分写入用户详情表
   * @author buddha <[email address]>
   * @return [type] [description]
   */
  public function autoScoreTast(){
    $max_day = intval( C('MAX_REFUND_CASH_DAY') );
    empty($max_day) && $max_day =15 ;
    $where = array(
        'o_status' => '202',
        'complete_time' => array(array('gt' ,0) ,array('lt' , (time() - $max_day*3600*24 )) ,'and' )
      );
    $order_arr = M('StoreOrder')->where($where)->Field('order_sn,id,uid')->select();
    foreach ($order_arr as $key => $value) {
        $map = array(
            'order_id' => $value['id'],
            'order_sn' => $value['order_sn'],
            'type'     => 'in',
            'memo'     => '购物订单完成赠送积分'
          );
        $res = M('ScoreLog')->where($map)->find();
        if ($res) {
            $data = array('status'=>1,'update_time'=>time());
            M('ScoreLog')->where($map)->save($data);
            M('Member')->where('uid='.$value['uid'])->setInc('score',$res['amount']);
        }
    }
  } 

  // 自动更新参团失败列表
  public function joinfail(){
    $where['etime'] = array('lt',time());
    $where['status'] = 1;
    $ids = M('Join')->where($where)->getField('id' ,true);
    //$ids = M('Join')->where('etime < '.time())->getField('id' ,true);
    if($ids){
      $ids = implode(',' ,$ids) ;
      M('Join')->where('id in ('.$ids.')')->save(array('status' => 0));
    }
    $this->handlenopay();
    $this->handlepayed(); 
  }
  // 处理团购中未付款的订单
  public function handlenopay(){
    $where['status']  = 0 ;
    $where['join_id'] = 0 ;
    $where['ltime']   = array( 'lt' ,time()) ; 
    $result = M('Join_order')->where($where)->getField('id' ,true);
    if(!$result){
      return false;
    }
    $arr = implode(',' ,$result);
    M('Join_order')->where(' id in ('.$arr.')')->setField(array('status' =>2));
  }
  // 处理团购中付了款但未成功拼团的订单
  public function handlepayed(){
    $where['etime']  = array('lt' , time());
    $where['status'] = array('eq' , 0); 
    $result = M('Join_list')->where($where)->getField('id' ,true);
     if(!$result){
      return false;
    }
    $arr = implode(',' ,$result);
    //发送通知
    $this->join_notice($arr);
    M('Join_list')->where(' id in ('.$arr.')')->setField(array('status' =>2));
    M('Join_order')->where(' join_id in ('.$arr.') and paytime = 0')->setField(array('status' =>2));
    $need = M('Join_order')->where('join_id in ('.$arr.') and paytime > 0')->getField('id' ,true);
    $this->doit($need);
  }
  // 处理退款
  protected function doit($ids){
    if(empty($ids)){
      return false;
    }
    $where['a.id']       = $map['id']      = array('in', $ids);
    $where['a.paytime']  = $map['paytime'] = array('gt', 0);
    if( M('Join_order')->where($map)->setField('status' ,2 ) ){
      //处理库存和退款
      $order_lists = D('Join_order')->alias('a')->join('LEFT JOIN __JOIN_LIST__ b on b.id=a.join_id')->where($where)->field('a.*,b.activity_id')->select();
      if($order_lists){
        foreach($order_lists as $k => $v){
          //商品库存处理
          $mapp['item_id'] = $requst['item_id']     = $v['item_id'];
          $mapp['join_id'] = $requst['activity_id'] = $v['activity_id'];
          $map['spc_code'] = $v['item_code'];
          $demo =  M('Join_item_spec')->where($requst)->find();
          if($demo ){
            M('Join_item_spec')->where($requst)->setInc('quantity', $v['total_quantity']);
          }
          M('Join_item')->where($mapp)->setInc('stock', $v['total_quantity']);
          M('Item')->where('id ='.$v['item_id'])->setDec('buynum', $v['total_quantity']);
          //第三方退款处理
          if($v['total_amount'] > 0){
            $payment = M('Payment')->getById($v['payment_id']);
            
            $payment_return = json_decode($payment['payment_return'], true);
            $trade_no = $payment_return['trade_no'];
            if(empty($trade_no)){
              $trade_no = $payment_return['transaction_id'];
            }
            if(empty($trade_no)){
              $trade_no = $payment('payment_sn');
            }
            $refund_data = array(
              'uid'          => $v['uid'],
              'order_id'     => $v['id'],
              'payment_type' => $payment['payment_type'],
              'trade_no'     => $trade_no,
              'refund_type'  => 'item',
              'amount'       => $v['total_amount'],
              'detail'       => '团购失败退款',
              'type'         => 2,
              'seller_status'=> 2,//卖家处理状态
              'refund_status'=> 2,//退款状态
            );
            D('Refund')->update($refund_data);
          }
        }
      }
     
    }
  }
  // 拼团失败 信息提示
  protected function join_notice($joinIds){
    $where['_string'] = 'join_id IN ('.$joinIds.')';
    $info = M('Join_order')->where($where)->Field('uid,join_sn,payment_id')->select();
    $data = array(
        'uid'     => 0,
        'title'   => '拼团失败通知',
        'content' => '亲，您的拼团订单拼团失败,订单编号为：%s',
        'create_time'=> NOW_TIME
      );
    foreach ($info as $value) {
      $cdata[]['to_uid'] = $value['uid'];
      $cdata[]['content'] = sprintf($data['content'],$value['join_sn']);
      $payment_sn = M('Payment')->where('id='.$value['payment_id'])->getField('payment_sn');
      if ($payment_sn) {
        $cdata[]['content'] .= ',我们会在48小时之内,退款给您！';
      }
      $cdata[]['title'] = $data['title'];
      $cdata[]['uid']   = 0;
      $cdata[]['create_time'] = $data['create_time'];
    }
    M('Message')->data($cdata)->addAll();
  }
  /**
   * 订单自动确认收货
   */
  public function AutoConfirmReceipt()
  {
      //限制天数
      $max_day = C('MAX_CONFIRM_RECEIPT_DAY');
      $max_day == 0 && $max_day = 7;
      $map['o_status'] = 201;
      $sOrderAll = M('StoreOrder')->where($map)->field('id,shipping_time,o_status')->select();
      if (empty($sOrderAll)) {
          return false;
      }
      foreach ($sOrderAll as $val) {
          if (time() - $val['shipping_time'] > $max_day * 86400) {
              $data['o_status'] = 202;
              $data['complete_time'] = NOW_TIME;
              $where['id'] = $val['id'];
              M('StoreOrder')->where($where)->save($data);
          }
      }

      $orderAll = M('Order')->where($map)->field('id,shipping_time,o_status')->select();
      if (empty($orderAll)) {
          return false;
      }
      foreach ($orderAll as $val) {
          if (time() - $val['shipping_time'] > $max_day * 86400) {
              $data['o_status'] = 202;
              $data['complete_time'] = NOW_TIME;
              $where['id'] = $val['id'];
              M('Order')->where($where)->save($data);
          }
      }
      /*
            if($max_day > 0){
            $map = array(
              'o_status' => 201, //待确认收货
              'shipping_time' => array('between', array(strtotime('2016-11-11 00:00:00'), time() - $max_day * 86400)), //限制时间内
            );
            $save_data = array(
              'o_status' => 202,
              'complete_time' => NOW_TIME
            );
            M('StoreOrder')->where($map)->save($save_data);
          }*/
  }

  /**
   * 自动下载非本地头像
   */
  public function DownLoadAvatar(){
    $where = array(
      'avatar' => array('LIKE', 'http%'),
    );
    $list = M('Member')->field('uid, avatar,reg_time')->where($where)->select();
    foreach($list as $line){
      if(@fopen($line['avatar'], 'r')){
        $info = read_file($line['avatar']);
        $file = '/Uploads/Avatar/'.date('Y/m/d', $line['reg_time']).'/'.$line['uid'].'.png';
        mkdir('.'.dirname($file), 0777, true);
        if(strlen($info) > 100){
          if(file_put_contents('.'.$file, $info)){
            M('Member')->where('uid='.$line['uid'])->save(array('avatar' => $file));
          }
        }
      }
    }
  }
    
  /**
   * 行为日志转存SQL
   * @author Justin <justin@jipu.com> 2015.5.13
   */
  public function actionLogRestore(){
    $table = 'jipu_action_log';
    $start = 0;
    $db = M('');
    //数据总数
    $result = $db->query("SELECT COUNT(*) AS count FROM `{$table}`");
    $count  = $result['0']['count'];
    if($count <= 50000){
      return;
    }
    while($count > $start){
      $this->_actionLog2sql($start);
      $start += 10000;
    }
    $sql = "TRUNCATE TABLE `{$table}`";
    $db->execute($sql);
    $db->execute("alter table `{$table}` AUTO_INCREMENT=".($count+1).";");
  }
  
  private function _actionLog2sql($start = 0){
    $path = C('DATA_BACKUP_PATH');
    if(!is_dir($path)){
      mkdir($path, 0755, true);
    }
    //读取备份配置
    $config = array(
      'path'     => realpath($path) . DIRECTORY_SEPARATOR,
    );
    $table = 'jipu_action_log';
    $db = M('');
    $result = $db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000");
    foreach ($result as $row) {
        $row = array_map('addslashes', $row);
        $sql = "INSERT INTO `{$table}` VALUES ('" . str_replace(array("\r","\n"),array('\r','\n'),implode("', '", $row)) . "');\n";
        file_put_contents($config['path'].'./actionLog-'.date('Ymd-His', NOW_TIME).'.sql', $sql,FILE_APPEND);
    }
  }
  
}
